﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCF20Model;
using System.Diagnostics;
using WiseLink.RDS.Resource;
using System.Web.Script.Serialization;
using System.Web.Services.Protocols;
using Microsoft.Win32;
using System.Reflection;

namespace CCF20Model
{
    public class ZICBase
    {
        public static string PID = "3";
        public static string Pwd = "123";
        protected static string ret;
        protected static VehicleModel vehicleModel;
        protected static FaultModel faultModel;
        protected static DeviceModel deviceModel;
        protected static VehicleMaintenanceModel maintenanceModel;
        protected static ModelFactory modelFactory;
        protected static JavaScriptSerializer jsonSerializer;
        protected static SoapHttpClientProtocol currentSvc;
        protected static string zicUrl;
        protected static string svcType;
        

        public ZICBase()
        {
            

        }

        static ZICBase()
        {
            zicUrl = zicUrl ?? GetZICUrl();
            svcType = svcType ?? GetSvcType();
            currentSvc = currentSvc ?? GetCurrentZICSvc();
            currentSvc.Url = zicUrl;
            jsonSerializer = new JavaScriptSerializer();
            modelFactory = new ModelFactory();
            vehicleModel = (VehicleModel)modelFactory.CreateModel(ModelName.VehicleModel);
            faultModel = (FaultModel)modelFactory.CreateModel(ModelName.FaultModel);
            deviceModel = (DeviceModel)modelFactory.CreateModel(ModelName.DeviceModel);
            maintenanceModel = (VehicleMaintenanceModel)modelFactory.CreateModel(ModelName.VehicleMaintenanceModel);
        }

        public static bool ValideReturnMessageFromZIC(string ret)
        {
            StackTrace stackTrace = new StackTrace();
            if (ret == null)
            {
                LoggerHelper.LogCCF20(string.Format("ZIC 调用:{0} 返回为空，请与智信通联系", stackTrace.GetFrame(1).GetMethod().Name));
                return false;
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("ZIC 调用:{0}返回值为{1}", stackTrace.GetFrame(1).GetMethod().Name, ret));
            }
            switch (ret.ToLower())
            {
                case "exist":
                    return true;
                case "true":
                    return true;
                case "false":
                    return false;
                case "loginerr":
                    Utility.ShowMessageBox(Message.ZIC_LoginError);
                    return false;
                case "client_error":
                    Utility.ShowMessageBox(Message.ZIC_AlreadyRegistered);
                    return true;
                case "shopid_error":
                    Utility.ShowMessageBox(Message.ZIC_IDSMismatch);
                    return false;
                case "not_sell":
                case "nosell":
                    Utility.ShowMessageBox(Message.ZIC_IDCNotSold);
                    return false;
                case "paraerr":
                case "err":
                    Utility.ShowMessageBox(Message.ZIC_DataError);
                    return false;
                case "idssame":
                    Utility.ShowMessageBox(Message.ZIC_SameIDS);
                    return false;
                case "no_fit":
                case "nofit":
                    Utility.ShowMessageBox(Message.ZIC_NotExistingIDC);
                    return false;
                case "replace_true":
                    Utility.ShowMessageBox(Message.ZIC_ReplaceSucceed);
                    return true;
                case "replace_false":
                    Utility.ShowMessageBox(Message.ZIC_ReplaceFailed);
                    return false;
                case "noexist":
                    Utility.ShowMessageBox(Message.ZIC_IDCNotRegistered);
                    return false;
                case "delfail":
                    Utility.ShowMessageBox(Message.ZIC_DeleteFailed);
                    return false;
                case "sim_use":
                    Utility.ShowMessageBox(Message.ZIC_SIMCardUsed);
                    return false;
                case "nopro":
                    Utility.ShowMessageBox(Message.ZIC_SNUserPwdMismatch);
                    return false;
                case "no_device":
                    Utility.ShowMessageBox(Message.ZIC_NoDevice);
                    return false;
                default:
                    Utility.ShowMessageBox(ret);
                    return true;
            }
        }

        

        protected static string GetZICUrl()
        {
            RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\WiseLink", true);
            zicUrl = (string)reg.GetValue("ZICUrl", string.Empty);
            if (string.IsNullOrEmpty(zicUrl))
            {
                throw new ArgumentNullException("Can't find the ZICUrl in the registry");
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("ZICBase ZIC Url ={0}", zicUrl));
            }
            return zicUrl;
        }


        protected static string GetSvcType()
        {
            RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\WiseLink", true);
            svcType = (string)reg.GetValue("CustomerType", string.Empty);
            if (string.IsNullOrEmpty(svcType))
            {
                throw new ArgumentNullException("Can't find the CustomerType in the registry");
            }
            else if (svcType.Contains(ZICType.ChinaMobile))
            {
                return ZICType.ChinaMobile;

            }else
            {
                return ZICType.eRDS;
            }

            
        }
        protected static SoapHttpClientProtocol GetCurrentZICSvc()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            Type currentType = null;
            
            if (svcType == ZICType.ChinaMobile)
            {
                currentType = assembly.GetTypes()
                                    .Where(t=>t.IsSubclassOf(typeof(SoapHttpClientProtocol)) && t.FullName.Contains(ZICType.ChinaMobile))
                                    .FirstOrDefault();


            }else
            {
                currentType = assembly.GetTypes()
                                    .Where(t=>t.IsSubclassOf(typeof(SoapHttpClientProtocol)) && t.FullName.Contains(ZICType.eRDS))
                                    .FirstOrDefault();

            }

            if (currentType != null)
            {
                currentSvc = (SoapHttpClientProtocol)assembly.CreateInstance(currentType.FullName, false);
                
                return currentSvc;
            }
            else
            {
                throw new ArgumentNullException(string.Format("Can't find the ZIC type {0}",svcType));
            }
        }


        public static bool RunMethod(string methodName, Object[] parameters)
        {
            LoggerHelper.LogCCF20(string.Format("RunMethod: Name={0}, Parameters={1}",methodName,  String.Join(",", parameters)));
            return ValideReturnMessageFromZIC(ExectueMethod(methodName,parameters));
        }
        public static string ExectueMethod(string methodName, Object[] parameters)
        {
            MethodInfo mi = currentSvc.GetType().GetMethods().Where(m => m.MemberType == MemberTypes.Method && m.Name.Equals(methodName)).FirstOrDefault();
            if (mi == null) throw new ArgumentException("Method not found in the current service");
            object returnobj = mi.Invoke(currentSvc, parameters);
            return returnobj.ToString();
        }
        
        public static bool DeviceUnRegister(Device device)
        {
            object[] parameters = new object[] {device.IDCSimNumber,
                                                PID,
                                                Pwd,
                                                device.DeviceKey };
            return RunMethod(ZICMethod.cancelproductRegister, parameters);

        }
        public static bool SpecialIDCRegister(Device device)
        {
            object[] parameters = new object[] {
                                                PID,
                                                Pwd,
                                                device.IDCSimNumber };
            return RunMethod(ZICMethod.SpecialIDcReg, parameters);
            

        }

        public static bool SpecialIDCUnRegister(Device device)
        {
            object[] parameters = new object[] {
                                                PID,
                                                Pwd,
                                                device.IDCSimNumber };
            return RunMethod(ZICMethod.cancelIDcReg, parameters);
            
        }

        public static bool IsSpecialIDC(Device device)
        {
            object[] parameters = new object[] {
                                                PID,
                                                Pwd,
                                                device.IDCSimNumber };

            return RunMethod(ZICMethod.IsSpIDC, parameters);
            
        }

    }
}
